<template>
    <view class="training" :style="{ minHeight: '100vh' }">
        <scroll-view class="nav-scroll" scroll-x :scroll-left="scrollLeft">
            <view class="nav-chapters">
                <view @click="handleNavChapters(item)" class="nav-chapters-item"
                    :class="{ 'active': chapterId == item.id }" v-for="(item, index) in courseData.chapters"
                    :key="index" :id="'nav-' + item.id">
                    <text>{{ item.title }}</text>
                </view>
            </view>
        </scroll-view>
        <view class="info-card">
            <view class="course-info">
                <!-- <view class="title">
                    <text class="course-name">{{ title }}</text>
                </view> -->
                <view class="time-box">
                    <template v-if="data.times && data.times.length > 0">
                        <view class="time-box-item" v-for="(timeSlot, index) in data.times" :key="index">
                            <view class="time-info-row">
                                <text class="label">培训时间 {{ data.times.length > 1 ? index + 1 : '' }}</text>
                                <text class="value">
                                    {{ parseTime(timeSlot.startTime, '{y}-{m}-{d}') }}
                                    {{ parseTime(timeSlot.startTime, '{h}:{i}') }}-{{ parseTime(timeSlot.endTime, '{h}:{i}') }}
                                </text>
                                <view class="status-tag" :class="getSingleTimeSlotStatus(timeSlot).class">
                                    {{ getSingleTimeSlotStatus(timeSlot).text }}
                                </view>
                            </view>
                            <view class="address-info-row" v-if="timeSlot.address && timeSlot.location" @click="handleNavigateToLocation(timeSlot)">
                                <text class="label">培训地点</text>
                                <text class="value address-link">{{ timeSlot.address }} (点击导航)</text>
                            </view>
                        </view>
                    </template>
                    <view class="time-box-item" v-else>
                        <text class="label">培训时间</text>
                        <text class="value">未安排</text>
                    </view>
                </view>
            </view>

            <view class="user-info">
                <view class="student-info" v-if="data.student">
                    <text class="subject" style="font-weight: bold;">{{ data.courseTitle }}{{ data.teamName }}</text>

                    <view class="info-item">
                        <text class="label">学员姓名</text>
                        <view class="info-value" style="display: flex; align-items: center;">
                            <image v-if="data.student?.avatar" :src="data.student.avatar" mode="aspectFill"
                                class="avatar"></image>
                            <text class="value">{{ data.student?.nickname || '--' }}</text>
                        </view>
                    </view>
                    <view class="info-item" v-if="data.student.phone">
                        <text class="label">手机号码</text>
                        <text class="value">{{ data.student.phone }}</text>
                    </view>
                    <view class="info-item">
                        <text class="label">身份证号</text>
                        <text class="value">{{ data.student?.identity || '--' }}</text>
                    </view>

                </view>
                <view class="qrcode-box" @click="previewQRCode(qrCodeValue)">
                    <view class="qrcode-wrapper">
                        <tkiQrcode ref="qrcode" :val="qrCodeValue" :size="200" mode="canvas" :lv="1" :id="canvasId"
                            @result="qrR" :options="{
                                margin: 0,
                                backgroundColor: '#ffffff',
                                foregroundColor: '#000000'
                            }"></tkiQrcode>
                    </view>
                    <text>培训专属二维码</text>
                    <text class="tip">点击放大</text>
                </view>
            </view>
        </view>
        <view class="project-list">
            <template v-if="!data.scoreModel">
                <view class="audit-card" v-for="(item, index) in data.chapterItems" :key="index">
                    <!-- {{ userinfo.teacher }} -->
                    <uv-alert type="warning"
                        v-if="userinfo.teacher && !data.times?.[0]?.teachers?.some(teacher => teacher.id === userinfo.id)"
                        :show-icon="true" description="非当前负责老师无法审核"></uv-alert>
                    <view class="popup-content-item">
                        <view class="popup-content-item-top">
                            <text class="item-label">项目名称</text>
                            <text class="item-title">{{ index + 1 }}. {{ item.title }}</text>
                        </view>
                        <view class="popup-content-item-center">
                            <view class="popup-content-item-center-box">
                                <text>负责老师</text>
                                <view class="teacher-list">
                                    <view class="teacher-item" v-if="data.times?.[0]?.teachers && data.times?.[0]?.teachers.length"
                                        v-for="(teacher, tIndex) in data.times?.[0]?.teachers" :key="tIndex">
                                        <image class="teacher-avatar" :src="teacher.avatar" mode="aspectFill"></image>
                                        <text class="teacher-name">{{ teacher.name }}</text>
                                    </view>
                                    <text v-else class="value">--</text>
                                </view>
                            </view>
                            <view class="popup-content-item-center-box">
                                <text>审核状态</text>
                                <text :class="getStatusClass(item.status)">{{ getStatusText(item.status) }}</text>
                            </view>
                            <view v-if="item.status == 2" class="popup-content-item-center-box reject-reason">
                                <text>拒绝理由</text>
                                <text class="reason-text">{{ item.remark || '无' }}</text>
                            </view>
                            <view v-if="item.status != 0" class="popup-content-item-center-box">
                                <text>审核人</text>
                                <view class="info-row">
                                    <image :src="item.teacherAvatar" mode="aspectFill" class="avatar"></image>
                                    <text>{{ item.teacherName || '--' }}</text>
                                </view>
                            </view>
                            <view v-if="item.status != 0" class="popup-content-item-center-box">
                                <text>审核时间</text>
                                <text>{{ parseTime(item.createDate) || '--' }}</text>
                            </view>
                        </view>
                        <view v-if="(userinfo.teacher && data.times?.[0]?.teachers?.some(teacher => teacher.id === userinfo.id))"
                            class="popup-content-item-footer">
                            <uv-button type="primary" size="small" @click="handleAudit(item)"
                                :class="{ 'btn-disabled': item.status === 1 }" :disabled="item.status === 1">
                                {{ item.checked ? '已审核' : '审核' }}
                            </uv-button>
                        </view>
                    </view>
                </view>
            </template>
            <template v-else>
                <view class="audit-card">
                    <view class="popup-content-item">
                        <view class="popup-content-item-top">
                            <text class="item-label">项目名称</text>
                            <text class="item-title">{{ data.title }}</text>
                        </view>
                        <view class="score-panel">
                            <view class="score-header">
                                <text class="title">模拟考试成绩</text>
                                <text class="exam-count">共考试 {{ data.scoreModel.examCount }} 次</text>
                            </view>
                            <view class="score-content">
                                <view class="score-item">
                                    <text class="label">最高分</text>
                                    <text class="value highlight">{{ data.scoreModel.maxScore }}</text>
                                </view>
                                <view class="score-item">
                                    <text class="label">最低分</text>
                                    <text class="value">{{ data.scoreModel.minScore }}</text>
                                </view>
                                <view class="score-history">
                                    <text class="label">历史分数</text>
                                    <view class="score-list">
                                        <text v-for="(score, index) in data.scoreModel.listScore" 
                                              :key="index" 
                                              class="score-tag"
                                              :class="{ 'highlight':  score > 85 }">
                                            {{ score }}
                                        </text>
                                    </view>
                                </view>
                                <view class="score-item">
                                    <text class="label">最后考试时间</text>
                                    <text class="value time">{{ parseTime(data.scoreModel.lastTime, '{y}-{m}-{d} {h}:{i}') }}</text>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </template>
            <uv-popup ref="auditPopup" mode="bottom" round="10" closeable :closeOnClickOverlay="false">
                <view class="audit-popup">
                    <view class="audit-popup-header">
                        <text class="title">审核信息</text>
                    </view>
                    <view class="audit-popup-content">
                        <view class="audit-info">
                            <view class="info-item">
                                <text class="info-label">科目名称</text>
                                <text class="info-value">{{ data.title || '--' }}</text>
                            </view>
                            <view class="info-item">
                                <text class="info-label">项目名称</text>
                                <text class="info-value">{{ chapterItem?.title || '--' }}</text>
                            </view>
                            <view class="info-item">
                                <text class="info-label">学生姓名</text>
                                <view class="info-value" style="display: flex; align-items: center;">
                                    <image :src="data.student?.avatar" mode="aspectFill" class="avatar"></image>
                                    <text>{{ data.student.nickname || '--' }}</text>
                                </view>
                            </view>
                            <view class="info-item">
                                <text class="info-label">身份证号码</text>
                                <text class="info-value">{{ data.student.identity || '--' }}</text>
                            </view>
                        </view>
                        <view class="divider"></view>
                        <uv-form ref="auditForm" :model="auditForm" :rules="auditRules" labelWidth="140rpx">
                            <uv-form-item label="审核结果" class="form-item">
                                <uv-switch v-model="auditForm.status" activeColor="#0086FF" inactiveColor="#fb4736"
                                    :activeValue="1" :inactiveValue="2" @change="handleSwitchChange"></uv-switch>
                                <text class="result-text"
                                    :style="{ color: auditForm.status === 1 ? '#0086FF' : '#fb4736' }">
                                    {{ auditForm.status === 1 ? '通过' : '拒绝' }}
                                </text>
                            </uv-form-item>

                            <uv-form-item class="form-item" v-if="auditForm.status === 2">
                                <text class="label">拒绝理由</text>
                                <uv-textarea v-model="auditForm.remark" placeholder="请输入拒绝理由" :maxlength="200"
                                    height="160"></uv-textarea>
                            </uv-form-item>
                        </uv-form>
                    </view>
                    <view class="audit-popup-footer">
                        <uv-button @click="cancelAudit">取消</uv-button>
                        <uv-button type="primary" @click="submitAudit">确认</uv-button>
                    </view>
                </view>
            </uv-popup>
            <!-- <view class="project-card" v-for="(item, index) in data.chapterItems" :key="index">
				<view class="project-header">
					<text class="project-name">培训项目：{{ item.title }}</text>
					<text class="status-tag" :class="getStatusClass(item.status)">
						{{ getStatusText(item.status) }}
					</text>
				</view>
				<view class="project-info">
					<view class="info-row">
						<text class="label">培训老师</text>
						<text class="value">{{ item.teacherName }}</text>
					</view>
					<view class="info-row">
						<text class="label">审核时间</text>
						<text class="value">{{ parseTime(item.createDate) || '--' }}</text>
					</view>
					<view class="reject-reason" v-if="item.status === 2">
						<text class="label">不合格理由</text>
						<text class="reason">{{ item.remark }}</text>
					</view>
				</view>
			</view> -->
        </view>

        <!-- Floating QR Code Button -->
       
    </view>
</template>

<script>
import { getChapterDetailList } from '@/http/user'
import { getCourseDetail } from '@/http/exam.js'
import { getTeamStudentList, getStudentChapterDetailList, checkedStudentProject } from '@/http/teacher.js'
import tkiQrcode from "@/components/tki-qrcode/tki-qrcode.vue"
import {
    getDetail
} from '@/http/user.js'

import { parseTime } from '@/utils/tools'
export default {
    components: {
        tkiQrcode
    },
    data() {
        return {
            parseTime,
            qrCodeValue: '',
            data: {
                student: {
                    avatar: '',
                    nickname: '',
                    phone: '',
                    identity: ''
                },
                chapterItems: [],
                times: [] // Ensuring times is initialized if not already
            },
            chapterId: '',
            auditRules: {
                remark: [{
                    required: true,
                    message: '请输入拒绝理由',
                    trigger: ['blur'],
                    type: 'string'
                }]
            },
            studentData: {},
            projectData: {
                chapterList: []
            },
            studentId: '',
            userinfo: {},
            chapterItem: {},
            auditForm: {
                status: 0,
                remark: ''
            },
            courseData: {}, // 课程数据
            courseId: '', // 课程id
            title: '', // 课程名称
            studentId: '', // 学生id
            scrollLeft: 0,
            isRefreshing: false,
            options: {}, // 扫码参数
            qrCodeReady: false, // 添加二维码准备状态
            canvasId: 'qrcode' + Date.now(), // 确保 canvasId 唯一
            qrImgUrl: ''
        }
    },
    computed: {
        // trainingStatus() {
        //     const now = Date.now();
        //     if (!this.data.times || this.data.times.length === 0) {
        //         return { text: '未设置', class: 'status-unknown' };
        //     }

        //     const validTimes = this.data.times
        //         .filter(t => t && t.startTime && t.endTime)
        //         .map(t => ({
        //             startTime: new Date(t.startTime).getTime(),
        //             endTime: new Date(t.endTime).getTime()
        //         }));

        //     if (validTimes.length === 0) {
        //         return { text: '未设置', class: 'status-unknown' };
        //     }

        //     let isOngoing = false;
        //     let allPending = true;
        //     let allEnded = true;

        //     for (const time of validTimes) {
        //         if (now >= time.startTime && now <= time.endTime) {
        //             isOngoing = true;
        //             break; 
        //         }
        //         if (now < time.startTime) {
        //             allEnded = false; 
        //         } else { 
        //             allPending = false;
        //         }
        //     }

        //     if (isOngoing) {
        //         return { text: '进行中', class: 'status-ongoing' };
        //     }

        //     if (allPending) {
        //         return { text: '未开始', class: 'status-pending' };
        //     }

        //     if (allEnded) {
        //         return { text: '已结束', class: 'status-ended' };
        //     }
            
        //     // Default for mixed states (some past, some future, none currently ongoing)
        //     return { text: '未开始', class: 'status-pending' };
        // }
    },
    onLoad(options) {
        const op = uni.getLaunchOptionsSync()
        console.log(options, op.scene, 'options参数1', [1047, 1011, 1012].includes(op.scene));
        this.options = options
        // 处理扫码进入的情况
        if ([1047, 1011, 1012].includes(op.scene)) {
            try {
                const qrUrl = decodeURIComponent(options.q)
                const params = this.GetWxMiniProgramUrlParam(qrUrl)
                console.log('解析的参数:', params);
                // 确保使用正确的参数名
                this.courseId = params.courseId
                this.studentId = params.studentId
                this.chapterId = params.chapterId
                this.loadData()
            } catch (error) {
                console.error('解析二维码参数失败:', error)
                this.handleParamError()
                return
            }
        } else
            // 处理正常链接进入的情况
            if (options.courseId && options.studentId) {
                uni.setNavigationBarTitle({ title: '培训安排' })
                console.log(options, '正常扫码，正常链接');
                this.courseId = options.courseId
                this.studentId = options.studentId
                this.chapterId = options.chapterId
                this.loadData()
            }
            // 参数错误的情况
            else {
                this.handleParamError()
                return
            }

        // 验证参数有效性
        if (!this.validateParams()) {
            this.handleParamError()
            return
        }
    },
    onShow() {
        // this.loadData()
    },
    onPullDownRefresh() {
        this.refreshData()
    },
    methods: {
        getSingleTimeSlotStatus(timeSlot) {
            const now = Date.now();
            if (!timeSlot || !timeSlot.startTime || !timeSlot.endTime) {
                return { text: '时间无效', class: 'status-unknown' }; 
            }
            const startTime = new Date(timeSlot.startTime).getTime();
            const endTime = new Date(timeSlot.endTime).getTime();

            if (now < startTime) {
                return { text: '未开始', class: 'status-pending' };
            }
            if (now > endTime) {
                return { text: '已结束', class: 'status-ended' };
            }
            return { text: '进行中', class: 'status-ongoing' };
        },
        // 验证参数
        validateParams() {
            return this.courseId && this.studentId &&
                !isNaN(Number(this.courseId)) &&
                !isNaN(Number(this.studentId))
        },

        // 处理参数错误
        handleParamError() {
            uni.showToast({
                title: '访问参数无效',
                icon: 'none'
            })
            setTimeout(() => {
                uni.navigateBack()
            }, 1500)
        },
        GetWxMiniProgramUrlParam(url) {
            let theRequest = {};
            try {
                // 1. 首先处理可能存在的 hash 部分
                let queryString = url;
                if (url.includes('#')) {
                    queryString = url.split('#')[1];
                }

                // 2. 提取查询参数部分
                if (queryString.includes('?')) {
                    queryString = queryString.split('?')[1];
                }

                // 3. 解析参数
                const params = queryString.split('&');
                for (const param of params) {
                    const [key, value] = param.split('=');
                    if (key && value) {
                        theRequest[key] = decodeURIComponent(value);
                    }
                }

                console.log('解析后的参数12:', theRequest);
            } catch (error) {
                console.error('解析URL参数失败:', error);
                throw error;
            }
            return theRequest;
        },
        async loadData() {
            try {
                uni.showLoading({
                    title: '加载中...',
                    mask: true
                })

                // 1. 获取用户详情
                const userDetailRes = await getDetail()
                const userData = userDetailRes.data

                // 保存用户信息到存储
                uni.setStorageSync('userinfo', userData)

                // 更新用户信息状态
                this.userinfo = {
                    ...userData,
                    phone: userData.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2'),
                    identity: userData.identity.replace(/(\d{6})\d{6}(\d{4})/, '$1****$2'),
                    avatarUrl: userData.avatar || 'https://img.qiananquang.com/minapp/avatar.png'
                }

                // 2. 获取课程详情
                console.log(this.courseId);

                const courseRes = await getCourseDetail({ courseId: this.courseId })
                this.courseData = courseRes.data
                console.log(courseRes, '课程详情');

                // 设置默认章节
                if (!this.chapterId && courseRes.data.chapters?.length) {
                    console.log(courseRes.data.chapters, '默认科目');
                    this.chapterId = courseRes.data.chapters[0].id
                }

                // 3. 加载章节数据
                await this.loadChapterData()
                
                // 4. 添加自动滚动到匹配位置的逻辑
                this.$nextTick(() => {
                    setTimeout(() => {
                        const query = uni.createSelectorQuery().in(this)
                        query.select(`#nav-${this.chapterId}`).boundingClientRect()
                        query.select('.nav-chapters').boundingClientRect()
                        query.exec(([itemRect, navRect]) => {
                            if (itemRect && navRect) {
                                const centerPosition = itemRect.left + itemRect.width / 2 - navRect.left
                                const scrollCenter = navRect.width / 2
                                this.scrollLeft = centerPosition - scrollCenter
                                // 使用uni.pageScrollTo进行滚动
                                uni.createSelectorQuery().in(this).select('.nav-scroll').boundingClientRect(rect => {
                                    if (rect) {
                                        const scrollView = uni.createSelectorQuery().in(this).select('.nav-scroll')
                                        scrollView.node(res => {
                                            if (res && res.node) {
                                                res.node.scrollLeft = this.scrollLeft
                                            }
                                        }).exec()
                                    }
                                }).exec()
                            }
                        })
                    }, 300) // 添加延时确保DOM已经渲染完成
                })
                uni.hideLoading()

            } catch (error) {
                console.error('加载数据失败:', error)
                this.userInfo = {}
                uni.showToast({
                    title: '加载失败，请重试',
                    icon: 'none'
                })
            } finally {
                uni.hideLoading()
            }
        },
        handleNavChapters(item) {
            uni.showLoading({
                title: '加载中...',
                mask: true
            })
            this.chapterId = item.id
            this.loadChapterData()
            // this.$nextTick(() => {
            //     const query = uni.createSelectorQuery().in(this)
            //     query.select(`#nav-${item.id}`).boundingClientRect()
            //     query.select('.nav-chapters').boundingClientRect()
            //     query.exec(([itemRect, navRect]) => {
            //         if (itemRect && navRect) {
            //             const centerPosition = itemRect.left + itemRect.width / 2 - navRect.left
            //             const scrollCenter = navRect.width / 2
            //             this.scrollLeft += centerPosition - scrollCenter
            //         }
            //     })
            // })
        },
        async loadChapterData() {
            try {
                let res;
                if (this.userinfo.teacher) {
                    res = await getStudentChapterDetailList({
                        uid: this.studentId,
                        chapterId: this.chapterId
                    });
                } else {
                    if(this.userinfo.id != this.studentId){
                        uni.showModal({
                            title: '请不要扫描其他学员二维码',
                            icon: 'none',
                            showCancel: false,
                            success: (res) => {
                                if (res.confirm) {
                                }
                            }
                        })
                    }
                    res = await getChapterDetailList({
                        chapterId: this.chapterId
                    });
                }
                console.log(res.data);
                
                // 确保数据结构完整
                this.data = {
                    ...this.data,
                    ...res.data,
                    student: {
                        ...this.data.student,
                        ...(res.data.student || {})
                    }
                }

                // Sort times by start time in ascending order
                if (this.data.times && Array.isArray(this.data.times)) {
                    this.data.times.sort((a, b) => {
                        const dateA = a.startTime ? new Date(a.startTime) : null;
                        const dateB = b.startTime ? new Date(b.startTime) : null;
                        const timeA = dateA && !isNaN(dateA.getTime()) ? dateA.getTime() : Infinity;
                        const timeB = dateB && !isNaN(dateB.getTime()) ? dateB.getTime() : Infinity;
                        if (timeA === Infinity && timeB === Infinity) return 0; // Keep original order for two invalid/missing times
                        return timeA - timeB;
                    });
                }

                console.log('章节数据:', this.data)

                // 只有在数据加载完成后才生成二维码
                if (this.data.student) {
                    this.generateQRCode()
                }
            } catch (error) {
                console.error('加载章节数据失败:', error)
                uni.showToast({
                    title: '加载章节数据失败',
                    icon: 'none'
                })
            }
        },
        generateQRCode() {
            if (!this.data?.student?.id || !this.courseId || !this.courseData?.title) {
                console.warn('生成二维码所需数据不完整')
                return
            }

            const qrData = `http://student.qiananquang.com/#/pages/subject/subject?studentId=${this.data.student.id}&courseId=${this.courseId}&chapterId=${this.chapterId}`
            console.log('二维码数据:', qrData)
            this.qrCodeValue = qrData

            this.$nextTick(() => {
                if (this.$refs.qrcode) {
                    this.$refs.qrcode._makeCode()
                }
            })
        },
        qrR(val) {
            this.qrImgUrl = val
        },
        previewQRCode(val) {
            uni.previewImage({
                urls: [this.qrImgUrl],
                success: () => {
                    console.log('预览成功')
                },
                fail: (err) => {
                    console.error('预览失败:', err)
                    uni.showToast({
                        title: '预览失败',
                        icon: 'none'
                    })
                }
            })
        },
        getStatusClass(status) {
            switch (status) {
                case 0: return 'status-pending'
                case 1: return 'status-pass'
                case 2: return 'status-reject'
                default: return ''
            }
        },
        getStatusText(status) {
            switch (status) {
                case 0: return '未审核'
                case 1: return '合格'
                case 2: return '不合格'
                default: return '--'
            }
        },
        handleAudit(item) {
            // if(item)
            console.log(item, 'item629');

            this.chapterItem = item
            this.auditForm = {
                status: item.status == 0 ? 1 : item.status,
                remark: item.remark
            }
            if (item.status === 1) return
            this.$refs.auditPopup.open()
        },
        handleSwitchChange(value) {
            // 切换为通过时清空拒绝理由
            if (value === 1) {
                this.auditForm.remark = ''
            }
        },
        async submitAudit() {
            if (this.auditForm.status === 2) {
                try {
                    await this.$refs.auditForm.validate()
                } catch (error) {
                    return
                }
            }

            try {
                const params = {
                    ...(this.chapterItem?.id ? { id: this.chapterItem.id } : {}),
                    itemId: this.chapterItem.itemId,
                    status: this.auditForm.status,
                    remark: this.auditForm.remark,
                    userId: this.studentId,
                    chapterId: this.chapterId,
                    teacherId: this.userinfo.id,
                    teacherName: this.userinfo.nickname,
                    teacherAvatar: this.userinfo.avatar,
                    title: this.chapterItem.title,
                    teamId: this.data.teamId,
                    checked: true
                }
                console.log(params, '提交审核', this.data);
                
                // return
                await checkedStudentProject(params)
                uni.showToast({
                    title: '审核成功',
                    icon: 'success'
                })
                this.$refs.auditPopup.close()
                this.resetAuditForm()
                this.loadData()
            } catch (err) {
                uni.showToast({
                    title: '审核失败',
                    icon: 'none'
                })
            }
        },
        resetAuditForm() {
            this.auditForm = {
                status: 1,
                remark: ''
            }
        },

        cancelAudit() {
            this.$refs.auditPopup.close()
        },
        async refreshData() {
            try {
                this.isRefreshing = true
                // 重新加载课程数据
                const courseRes = await getCourseDetail({ courseId: this.courseId })
                this.courseData = courseRes.data

                // 重新加载章节数据
                if (this.chapterId) {
                    const chapterRes = await getStudentChapterDetailList({
                        uid: this.studentId,
                        chapterId: this.chapterId
                    })
                    this.data = chapterRes.data
                    // Sort times by start time in ascending order
                    if (this.data.times && Array.isArray(this.data.times)) {
                        this.data.times.sort((a, b) => {
                            const dateA = a.startTime ? new Date(a.startTime) : null;
                            const dateB = b.startTime ? new Date(b.startTime) : null;
                            const timeA = dateA && !isNaN(dateA.getTime()) ? dateA.getTime() : Infinity;
                            const timeB = dateB && !isNaN(dateB.getTime()) ? dateB.getTime() : Infinity;
                            if (timeA === Infinity && timeB === Infinity) return 0; // Keep original order for two invalid/missing times
                            return timeA - timeB;
                        });
                    }
                }

                uni.showToast({
                    title: '刷新成功',
                    icon: 'success'
                })
            } catch (error) {
                console.error('刷新数据失败:', error)
                uni.showToast({
                    title: '刷新失败',
                    icon: 'none'
                })
            } finally {
                this.isRefreshing = false
                // 停止下拉刷新动画
                uni.stopPullDownRefresh()
            }
        },
        // 在组件销毁时重置状态
        onUnload() {
            this.qrCodeReady = false
        },
        handleNavigateToLocation(timeSlot) {
            if (!timeSlot || !timeSlot.location || typeof timeSlot.location !== 'string') {
                uni.showToast({
                    title: '位置信息无效',
                    icon: 'none'
                });
                return;
            }

            const parts = timeSlot.location.split(',');
            if (parts.length !== 2) {
                uni.showToast({
                    title: '位置坐标格式错误',
                    icon: 'none'
                });
                return;
            }

            const latitude = parseFloat(parts[0]);
            const longitude = parseFloat(parts[1]);

            if (isNaN(latitude) || isNaN(longitude)) {
                uni.showToast({
                    title: '无效的经纬度',
                    icon: 'none'
                });
                return;
            }

            uni.openLocation({
                latitude: latitude,
                longitude: longitude,
                name: timeSlot.address || '培训地点',
                address: timeSlot.address || '',
                success: function () {
                    console.log('打开地图成功');
                },
                fail: function (err) {
                    console.error('打开地图失败:', err);
                    uni.showToast({
                        title: '打开地图失败',
                        icon: 'none'
                    });
                }
            });
        },
    }
}
</script>

<style lang="scss" scoped>
.training {
    padding: 30rpx;
    background: #e8e8e8;
    min-height: 100vh;

    .info-card {
        background: #FFFFFF;
        border-radius: 16rpx;

        margin-bottom: 30rpx;
        box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);

        .course-info {
            border-bottom: 2rpx solid #EBEDF0;
            padding: 10rpx 0;
            background: #e4e4e473;

            .title {
                padding: 30rpx 30rpx 20rpx 30rpx;

                .course-name {
                    font-size: 32rpx;
                    font-weight: bold;
                    color: #333;
                    display: block;
                }

                .subject {
                    font-size: 26rpx;
                    color: #666;
                    display: block;

                }
            }

            .time-box {
                position: relative;

                .status-tag {
                    padding: 4rpx 12rpx;
                    border-radius: 20rpx;
                    font-size: 22rpx;
                    font-weight: 500;
                    margin-left: auto;

                    &.status-pending {
                        background: #E6F7FF;
                        color: #1890FF;
                    }

                    &.status-ongoing {
                        background: #F6FFED;
                        color: #52C41A;
                    }

                    &.status-ended {
                        background: #FFF1F0;
                        color: #FF4D4F;
                    }

                    &.status-unknown {
                        background: #F5F5F5;
                        color: #999;
                    }
                }

                .time-box-item {
                    display: flex;
                    flex-direction: column;
                    padding: 20rpx 30rpx;
                    border-bottom: 1rpx solid #f0f0f0;

                    &:last-child {
                        border-bottom: none;
                    }

                    .time-info-row, .address-info-row {
                        display: flex;
                        align-items: center;
                        width: 100%;
                        margin-bottom: 10rpx;
                    }
                    
                    .address-info-row {
                        margin-bottom: 0;
                    }

                    .label {
                        font-size: 26rpx;
                        color: #666;
                        margin-right: 15rpx;
                        flex-shrink: 0;
                    }

                    .value {
                        font-size: 26rpx;
                        color: #333;
                    }
                    
                    .address-link {
                        color: $uni-color-primary;
                        cursor: pointer;
                        flex-grow: 1;
                    }
                }
            }
        }

        .user-info {
            display: flex;
            justify-content: space-between;
            padding: 30rpx;

            .student-info {
                flex: 1;
                padding-right: 30rpx;

                .info-item {
                    margin-bottom: 8rpx;
                    display: flex;
                    align-items: center;

                    .avatar {
                        width: 40rpx;
                        height: 40rpx;
                        border-radius: 50%;
                        margin-right: 12rpx;
                    }

                    .label {
                        font-size: 26rpx;
                        color: #666;
                        margin-right: 20rpx;
                        display: inline-block;
                    }

                    .value {
                        font-size: 26rpx;
                        color: #333;
                    }
                }
            }

            .qrcode-box {
                text-align: center;

                :deep(.uv-qrcode) {
                    width: 120rpx;
                    height: 120rpx;
                    margin-bottom: 10rpx;
                }

                text {
                    font-size: 24rpx;
                    color: #666;
                    display: block;
                }

                .tip {
                    color: #0086FF;
                    font-size: 22rpx;
                    margin-top: 6rpx;
                }
            }
        }
    }

    .project-list {
        .audit-card {
            background: #fff;
            border-radius: 12rpx;
            padding: 24rpx;
            margin-bottom: 20rpx;
            box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

            &:last-child {
                margin-bottom: 0;
            }
        }

        .popup-content-item-top {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20rpx;

            .item-label {
                color: #666;
                font-size: 28rpx;
            }

            .item-title {
                color: #333;
                font-size: 28rpx;
                font-weight: bold;
            }
        }

        .popup-content-item-center {
            .popup-content-item-center-box {
                display: flex;
                justify-content: space-between;
                align-items: center;
                padding: 16rpx 0;
                border-bottom: 2rpx solid #f5f5f5;

                .teacher-list {
                    flex: 1;
                    display: flex;
                    flex-wrap: wrap;
                    gap: 16rpx;

                    .teacher-item {
                        display: flex;
                        align-items: center;
                        background: #F5F6F8;
                        padding: 8rpx 16rpx;
                        border-radius: 24rpx;

                        .teacher-avatar {
                            width: 32rpx;
                            height: 32rpx;
                            border-radius: 50%;
                            margin-right: 8rpx;
                        }

                        .teacher-name {
                            font-size: 24rpx;
                            color: #333;
                        }
                    }
                }

                .info-row {
                    display: flex;
                    align-items: center;
                    justify-content: space-between;
                }

                .avatar {
                    width: 40rpx;
                    height: 40rpx;
                    border-radius: 50%;
                    margin-right: 12rpx;
                }

                &:last-child {
                    border-bottom: none;
                }

                text:first-child {
                    color: #666;
                    font-size: 26rpx;
                }

                text:last-child {
                    font-size: 26rpx;
                }

                .status-pass {
                    color: #0086FF;
                }

                .status-reject {
                    color: #fb4736;
                }

                .status-pending {
                    color: #999;
                }

                &.reject-reason {
                    background: #FFF0F0;
                    border-radius: 8rpx;
                    padding: 16rpx;
                    margin: 10rpx 0;

                    .reason-text {
                        color: #fb4736;
                        flex: 1;
                        margin-left: 20rpx;
                        text-align: right;
                    }
                }
            }
        }

        .popup-content-item-footer {
            display: flex;
            justify-content: flex-end;
            margin-top: 20rpx;
            padding-top: 20rpx;
            border-top: 2rpx solid #f5f5f5;

            .btn-disabled {
                background: #999 !important;
                opacity: 0.6;
            }

            :deep(.uv-button) {
                // margin-left: 16rpx;
                min-width: 120rpx;
            }

            :deep(.uv-button--small) {
                padding: 8rpx 20rpx;
                height: 56rpx;
                line-height: 40rpx;
                font-size: 26rpx;
            }
        }
    }

    .audit-popup {
        height: 100%;
        display: flex;
        flex-direction: column;

        &-header {
            padding: 30rpx;
            border-bottom: 2rpx solid #eee;

            .title {
                font-size: 32rpx;
                font-weight: bold;
                color: #333;
            }
        }

        &-content {
            flex: 1;
            padding: 30rpx;
            overflow-y: auto;

            .audit-info {
                margin-bottom: 30rpx;

                .info-item {
                    display: flex;
                    align-items: center;
                    margin-bottom: 20rpx;

                    &:last-child {
                        margin-bottom: 0;
                    }

                    .info-label {
                        width: 140rpx;
                        font-size: 28rpx;
                        color: #666;
                    }

                    .avatar {
                        width: 40rpx;
                        height: 40rpx;
                        border-radius: 50%;
                        margin-right: 12rpx;
                    }

                    .info-value {
                        flex: 1;
                        font-size: 28rpx;
                        color: #333;
                        font-weight: 500;
                    }
                }
            }

            .divider {
                height: 2rpx;
                background: #eee;
                margin: 30rpx 0;
            }

            .form-item {
                margin-bottom: 30rpx;

                .label {
                    display: block;
                    margin-bottom: 20rpx;
                    font-size: 28rpx;
                    color: #333;
                }

                .result-text {
                    margin-left: 20rpx;
                    font-size: 28rpx;
                }
            }
        }

        &-footer {
            padding: 20rpx 30rpx;
            border-top: 2rpx solid #eee;
            display: flex;
            justify-content: flex-end;
            gap: 20rpx;
        }
    }

    .nav-scroll {
        background: #fff;
        margin-bottom: 20rpx;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);

        &::-webkit-scrollbar {
            display: none;
        }
    }

    .nav-chapters {
        display: flex;
        padding: 20rpx 30rpx;
        white-space: nowrap;

        .nav-chapters-item {
            position: relative;
            padding: 10rpx 20rpx;
            margin-right: 20rpx;
            border-radius: 32rpx;
            background: #F5F5F5;
            transition: all 0.3s ease;
            flex-shrink: 0;
            display: inline-block;

            &:last-child {
                margin-right: 0;
            }

            text {
                font-size: 28rpx;
                color: #666;
                font-weight: 500;
                white-space: nowrap;
            }

            &.active {
                background: #0086FF;

                text {
                    color: #fff;
                }

                &::after {
                    content: '';
                    position: absolute;
                    bottom: -10rpx;
                    left: 50%;
                    transform: translateX(-50%);
                    border: 6rpx solid transparent;
                    border-top-color: #0086FF;
                }
            }

            &:active {
                opacity: 0.8;
                transform: scale(0.98);
            }
        }
    }

    .score-panel {
        background: #FFFFFF;
        border-radius: 12rpx;
        padding: 24rpx;
        margin: 20rpx 0;
        box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);

        .score-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 24rpx;
            padding-bottom: 16rpx;
            border-bottom: 2rpx solid #F5F6F8;

            .title {
                font-size: 32rpx;
                font-weight: bold;
                color: #333;
            }

            .exam-count {
                font-size: 26rpx;
                color: #666;
                background: #F5F6F8;
                padding: 4rpx 16rpx;
                border-radius: 20rpx;
            }
        }

        .score-content {
            .score-item {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin-bottom: 20rpx;
                padding: 16rpx;
                background: #F8F9FC;
                border-radius: 8rpx;

                .label {
                    font-size: 28rpx;
                    color: #666;
                }

                .value {
                    font-size: 32rpx;
                    color: #333;
                    font-weight: 500;

                    &.highlight {
                        color: #0086FF;
                        font-weight: bold;
                    }

                    &.time {
                        font-size: 26rpx;
                        color: #666;
                    }
                }
            }

            .score-history {
                margin-bottom: 20rpx;
                padding: 16rpx;
                background: #F8F9FC;
                border-radius: 8rpx;

                .label {
                    font-size: 28rpx;
                    color: #666;
                    margin-bottom: 16rpx;
                    display: block;
                }

                .score-list {
                    display: flex;
                    flex-wrap: wrap;
                    gap: 12rpx;

                    .score-tag {
                        padding: 8rpx 20rpx;
                        background: #E8E8E8;
                        border-radius: 20rpx;
                        font-size: 26rpx;
                        color: #333;

                        &.highlight {
                            background: #E6F7FF;
                            color: #0086FF;
                        }
                    }
                }
            }
        }
    }

}
</style>
